"""Test case for XMLRPC class"""
import sys
import os
sys.path.append(os.path.abspath('..'))
import unittest
import logging
import xmlrpclib
import time
from service.XMLRPC import XMLRPC

class MyObj:
    """ Test instance,we will use XMLPRC to bind it on ports"""
    def __init__ (self):
        """Init Code here"""
        pass

    def TestFunc(self,a,b):
        """This a test function. """
        return a+b

class TestXMLRPC (unittest.TestCase):
    """ Test Case for XML-RPC"""
    def setUp (self):
        """ This is the way we start XMLRPC on 127.0.0.1"""
        ip='127.0.0.1'
        port_start = 8000
        pool_size = 15
        logging.basicConfig()
        logging.getLogger().setLevel(logging.ERROR)
        XMLRPC(ip,port_start,pool_size)

    def test_request_release (self):
        """ Test Request Report and Release Port"""
        print self.__doc__
        #time.sleep(5)
        aobj=MyObj()
        #Since we haven't use any port.(all,available)=(15,15)
        self.assertEqual((15,15), XMLRPC.rpcDaemon.Report())
        #get port
        port_num = XMLRPC.rpcDaemon.RequestPort(aobj)
        self.assertEqual((15,14), XMLRPC.rpcDaemon.Report())
        #release port
        XMLRPC.rpcDaemon.ReleasePort(port_num)
        self.assertEqual((15,15), XMLRPC.rpcDaemon.Report())
        print "Test port pool overflow"
        p = []
        for i in range(15):
            p.append(XMLRPC.rpcDaemon.RequestPort(aobj))
        self.assertEqual((15,0), XMLRPC.rpcDaemon.Report())
        #We use up all port pool, so next request will raise Exception
        self.assertRaises(Exception, \
                              XMLRPC.rpcDaemon.RequestPort, aobj)
        for i in p:
            XMLRPC.rpcDaemon.ReleasePort(i)
        #if release none exists port
        print "Test release wrong port"
        self.assertRaises(Exception, \
                              XMLRPC.rpcDaemon.ReleasePort, 12345)

    def test_bind_func (self):
        """Test functions on port """
        print self.__doc__
        aobj=MyObj()
        port = XMLRPC.rpcDaemon.RequestPort(aobj)
        server = xmlrpclib.ServerProxy('http://localhost:'+str(port))
        print "Test Reomte function"
        print "2+3=",server.TestFunc(2,3)
        XMLRPC.rpcDaemon.ReleasePort(port)


if __name__ == '__main__':
   unittest.main()





